package com.mojawa.mj_util.location

import android.location.Location

class MJLocationDataManager() {
    private var points: MutableList<AmapLatLng> = mutableListOf()  // 点的集合
    var totalDistance: Double = 0.00 // 距离
    var presentPoints: AmapLatLng? = null

    /**
     * 添加点
     */
    fun addPoint(newPoints: List<AmapLatLng>?) {
        if (newPoints.isNullOrEmpty()) return

        // 将新点添加到已有点的集合中
        val lastPoint = points.lastOrNull()
        for (newPoint in newPoints) {
            // 仅当新点与上一个点不同的时候，才添加
            if (lastPoint == null || newPoint != lastPoint) {
                points.add(newPoint)
                // 如果当前有至少两个点，计算距离
                if (points.size >= 2) {
                    val lastTwoPoints = points.takeLast(2)

                    val distance = calculateDistance(lastTwoPoints)
                    if (distance <= 30) { // 距离小于等于30米才计入
                        totalDistance += distance
                    }
                }
            }
        }
    }

    fun clearPoints() {
        points.clear()
    }

    fun saveLocationData(points: List<AmapLatLng>, totalDistance: Double) {
        this.points.addAll(points)  // 将新的点添加到集合中，累积数据
        this.totalDistance += totalDistance
    }

    // 获取到所有点
    fun getPoints(): List<AmapLatLng> {
        return points
    }

    /**
     * 获取到当前点
     */
    fun getPoint(): AmapLatLng? {
        return presentPoints
    }

    /**
     * 使用 Google Maps 的 Location API 来计算两点之间的距离
     */
    private fun calculateDistance(newPoints: List<AmapLatLng>): Float {
        val point1 = newPoints[0]
        val point2 = newPoints[1]

        val result = FloatArray(1)

        // 使用 Android 的 Location API 计算两点之间的距离（以米为单位）
        Location.distanceBetween(
            point1.latitude, point1.longitude,
            point2.latitude, point2.longitude,
            result
        )

        return result[0] // 返回两点之间的距离，单位为米
    }
}
